System Design Interview Crash Course
Rate this course
Ask Author
Contribute
Back to course home

38% completed

Vote For New Content
Introduction
Course Overview
Who this Course Is for
How to Cover the Lessons
Day 1: Content Delivery & Media
Design YouTube
Design Netflix
Day 2: Key-Value & Caching Internals
Design a Distributed Cache (like Redis)
Design a Key-Value Store (like DynamoDB)
Day 3: Chat & Real-time Communication
Design WhatsApp
Design Discord
Day 4: Reliability & Observability
Design a Distributed Rate Limiter
Design a Metrics & Monitoring System (like Datadog/Prometheus)
Day 5: Storage & Retrieval (Blob & File)
Design Amazon S3
Design Google Ads
Day 6: E-Commerce & Transactions
Design Amazon Shopping Cart
Design Stripe Payment Gateway
Design Stock Exchange
Design Facebook “People You May Know”
Design LinkedIn Connections
Design Twitter Timeline
Design a Collaborative Whiteboard (Miro)
Design Google Docs
Design an Ad Click Aggregator
Design a Live Comment Streaming Service (Twitch Chat)
Design a Code Deployment System
Design an API Gateway
Design Amazon Lambda
Design ChatGPT
Design Typeahead/Autocomplete
Design Google Search
Design AirBnB
Design Uber/Lyft
Design a Distributed Lock Manager (like Chubby)
Design a Distributed Job Scheduler (like Cron)
Final Words
Design Amazon Shopping Cart
Image

Here is the step-by-step system design for the Amazon Shopping Cart.

1. Problem Definition and Scope

We are designing the backend for the Amazon Shopping Cart. This is a temporary storage area where users hold items they intend to purchase. It acts as the bridge between browsing products and the final checkout.

  • User Groups:
    • Shoppers: Add items, update quantities, and view the cart.

    • The System: Merges anonymous guest carts into user accounts when they log in.

  • Scope:
    • In Scope: Adding/removing items, updating quantities, viewing the cart, cross-device persistence, and handling guest-to-user cart merging.

    • Out of Scope: The checkout process, payment processing, product search, and complex inventory management (we will assume a simple availability check).

Image

2. Clarify functional requirements

Must Have:

  • Add Item: User can add a product to their cart.

  • Update Quantity: User can increase or decrease the quantity of an item.

  • Remove Item: User can delete an item from the cart.

  • View Cart: User can see all items, current prices, and the estimated total.

  • Persistence: The cart must persist across devices (e.g., add on mobile, view on desktop).

  • Cart Merge: If a user adds items as a guest and then logs in, the guest items must be merged into their saved account cart.

Nice to Have:

  • Soft Inventory Check: Check if an item is in stock before adding (but don't strictly reserve it yet).

  • Price Change Alert: Notify the user if an item's price has changed since it was added.

Image

3. Clarify non-functional requirements

  • Target Users: 100 Million Daily Active Users (DAU).

  • Read vs. Write: High write volume compared to most apps. Users constantly "Add to Cart" or modify quantities.

    • Assume a 1:5 write-to-read ratio.
  • Latency: Ultra-low latency is critical.

    • Writes (Add to Cart): < 100ms. If this is slow, users stop shopping.
    • Reads (View Cart): < 100ms.
  • Availability: High Availability (99.99%) is preferred over Strong Consistency. We must never reject an "Add to Cart" request, even if the database is busy.

  • Data Retention: Items typically stay in the cart for a long time (e.g., 30 days) to encourage eventual purchase.

  • Consistency: Eventual consistency is acceptable for cross-device syncing, but the current device should reflect changes instantly.

Image

4. Back of the envelope estimates

  • Traffic Estimates:
    • 100M DAU.
    • Average writes: 5 per user (add/update) 500M writes/day.
      • writes per second (WPS).
    • Average reads: 25 per user (view pages) 2.5B reads/day.
      • reads per second (RPS).
    • Peak Traffic: Amazon has massive spikes (Prime Day).1 Let's multiply by 5.
      • Peak Writes: ~30,000 WPS.
      • Peak Reads: ~150,000 RPS.
  • Storage Estimates:
    • A cart item is small: ItemID (UUID), Qty (Int), Timestamp. ~100 bytes.

    • Average cart has 5 items = 500 bytes. With metadata, let's say 1 KB per active cart.

    • 100M active carts 1 KB = 100 GB of hot data per day.

    • This is relatively small. We can keep the active set in memory (Redis) easily.

Image

5. API design

We will use a REST API. The client identifies the user via a Session-Token (for guests) or an Auth-Token (for logged-in users) in the headers.

  • GET /v1/cart
    • Description: Fetches current items and totals.
    • Response: JSON list of items (enriched with name, image, price) and total cost.
    • Status: 200 OK.
  • POST /v1/cart/items
    • Description: Adds an item.
    • Request: { "product_id": "p_123", "quantity": 1 }
    • Response: Updated cart summary (e.g., total item count).
    • Status: 201 Created.
  • PUT /v1/cart/items/{product_id}
    • Description: Updates quantity.
    • Request: { "quantity": 3 }
    • Status: 200 OK.
  • DELETE /v1/cart/items/{product_id}
    • Status: 204 No Content.
  • POST /v1/cart/merge
    • Description: Merges an anonymous session cart into a logged-in user cart.
    • Request: { "guest_session_id": "sess_abc" }
    • Status: 200 OK.

6. High level architecture

We need a system that handles high concurrency and prioritizes availability.

Flow: Client Load Balancer Cart Service Redis Cache NoSQL Database

Components:

  1. Client: Web or Mobile App. Maintains a local Session ID if the user is not logged in.

  2. Load Balancer: Distributes traffic to application servers.

  3. Cart Service: A stateless microservice.

    • Handles logic for adding/removing items.
    • Talks to Product Service to get fresh prices/names (we don't store product names in the cart DB to avoid stale data).
    • Talks to Inventory Service for soft stock checks.
  4. Redis Cache: Stores the active carts for super-fast reads.

  5. NoSQL Database (DynamoDB): The "Source of Truth." Chosen because carts are simple Key-Value data (lookup by UserID) and it scales writes horizontally very well.

Image

7. Data model

We will use NoSQL (DynamoDB). A relational database is overkill because we don't need complex joins. We just need to look up a cart by User ID.

Table: CartItems

  • Partition Key (PK): user_id (or session_id). Distributes data across nodes.
  • Sort Key (SK): item_id. Allows us to access/update specific items efficiently.
user_id (PK)item_id (SK)quantityadded_at
user_123prod_A2167241000
user_123prod_B1167241005
guest_abcprod_A1167241010

Why this structure?

  • Efficiency: We can fetch the whole cart by querying PK = user_123.
  • Granularity: We can update the quantity of just prod_A without rewriting the whole cart object.
  • Scalability: As users grow, DynamoDB automatically partitions data based on the PK.

8. Core flows end-to-end

We will look at the three most critical interactions in the Shopping Cart system. These flows illustrate how data moves through our architecture, how we handle high traffic, and how we ensure a seamless user experience.

Flow 1: Add Item to Cart (The Write Path)

This flow focuses on low latency. When a user clicks "Add to Cart," we want the feedback to be near-instant so they can keep shopping.

  1. Client Request:
    • The user clicks "Add to Cart" on a product page.
    • The client sends a POST /cart/items request with the product_id and quantity.
    • The Load Balancer receives the request and forwards it to one of the stateless Cart Service instances.
  2. Input Validation & Soft Stock Check:
    • The Cart Service first validates the input (e.g., ensures quantity is a positive number).
    • Soft Check: The service makes a quick remote procedure call (RPC) to the Inventory Service.
    • Why a "soft" check? We check if the item is generally available, but we do not lock or reserve the inventory yet. Reserving inventory at this stage creates too much database contention. We only strictly reserve items during the final checkout.
  3. Database Write (Persistence):
    • Once validated, the Cart Service writes the item to the NoSQL Database (DynamoDB).
    • It performs a PUT operation using the User_ID as the Partition Key and Item_ID as the Sort Key. This ensures the item is added to that specific user's bucket efficiently.
  4. Cache Update (Write-Through):
    • Immediately after writing to the database, the Cart Service updates the Redis Cache.
    • It updates the entry for cart:{user_id} with the new list of items.
    • Why? This ensures that if the user immediately navigates to the "View Cart" page, they see the new item instantly without hitting the database again.
  5. User Feedback:
    • The service returns a 200 OK status to the client.
    • The client UI updates the cart icon counter (e.g., from 2 items to 3 items).
Image

Flow 2: View Cart (The Read Path)

This is the most frequent operation. Users view their cart often to check totals. This flow is read-heavy and requires "Data Hydration."

  1. Client Request:
    • The user navigates to the Cart page. The client sends a GET /cart request.
  2. Cache Look-Aside:
    • The Cart Service first checks the Redis Cache using the key cart:{user_id}.
    • Cache Hit (Fast Path): If the cart data is found, we retrieve the list of item_ids and quantities directly from memory. This happens 90% of the time.
    • Cache Miss (Slow Path): If the cache is empty (e.g., expired), the service queries DynamoDB to fetch all items for that User_ID, updates Redis, and proceeds.
  3. Data Hydration (Enrichment):
    • The cart database is "slim"—it only stores { item_id: "A", qty: 1 }. It does not know the product's name, current price, or image URL.
    • To show the user a meaningful page, the Cart Service must "hydrate" this data.
    • It sends a batch request to the Product Service (or the Product Catalog Cache) for every item_id in the cart.
    • Why not store prices in the Cart DB? Prices change. If a user added a TV yesterday at $500, and today it is $450, the cart view must reflect the current $450 price, not the stale data.
  4. Response Construction:
    • The Cart Service merges the quantity data (from Cart DB) with the metadata (from Product Service).
    • It calculates the estimated total cost.
    • The full JSON response is sent back to the client to render the page.
Image

Flow 3: The "Merge" (Guest to User)

This is a complex but essential flow. It happens when a user starts shopping anonymously (Guest) and then logs into their existing account. We must ensure they don't lose the items they added as a guest.

  1. Trigger:
    • The user logs in successfully. The client app detects that a local "Guest Session" exists and sends a POST /cart/merge request, containing the guest_session_id.
  2. Fetch Both Carts:
    • The Cart Service performs two parallel reads from DynamoDB:
      • Fetch the temporary cart using the guest_session_id.
      • Fetch the saved cart using the authenticated user_id.
  3. In-Memory Union Logic:
    • The service loads both lists into memory and runs a merge algorithm:
      • New Items: If an item exists in the Guest cart but not the User cart, add it.
      • Duplicates: If an item exists in both, sum the quantities (e.g., 1 guest item + 2 saved items = 3 total).
      • Limits: Cap the quantity if the sum exceeds the allowed limit (e.g., max 10 per item).
  4. Bulk Write & Cleanup:
    • The Service saves the newly merged list to the user_id partition in DynamoDB.
    • It deletes the old guest_session_id data to free up storage space.
  5. Refresh Cache:
    • The new merged cart is written to Redis under cart:{user_id} so the user sees the combined items immediately upon redirection to the checkout or home screen.
Image

9. Caching and read performance

  • Cache Store: Redis Cluster.
  • Key: cart:{user_id}.
  • Value: A serialized JSON list of items [{id: "A", qty: 2}, ...].
  • Strategy: Write-Through.
    • Every write to the DB also updates the Cache. This prevents "stale reads" where a user adds an item but doesn't see it in the list immediately.
  • Product Caching: Crucially, we also cache Product Metadata (Price, Name, Image) separately. The Cart Service hits this "Product Cache" heavily during the View Cart flow to avoid overloading the Product Service.
  • TTL: Set a TTL of 24 hours. If a user stops shopping, their cart expires from RAM (cache) but stays in the DB (disk).

10. Storage, indexing and media

  • Primary Storage: DynamoDB.
    • We choose "On-Demand" capacity mode initially to handle unpredictable traffic, then switch to "Provisioned" for predictable costs.
  • Media: The Cart Service does not store images.
  • Indexes:
    • Primary Index: Partition Key = user_id, Sort Key = item_id.
    • TTL: We enable DynamoDB's Time-To-Live feature on a last_updated attribute. We can auto-delete guest carts that haven't been touched in 30 days to save storage.

11. Scaling strategies

  • Sharding (Partitioning):
    • Data is naturally sharded by user_id.
    • DynamoDB handles the distribution of these partitions across physical servers.2 Since User A's cart is independent of User B's, this scales infinitely.
  • Replication:
    • We use DynamoDB Global Tables to replicate data across regions (e.g., US-East and US-West).3
    • If US-East goes down, we route traffic to US-West, and the user's cart is already there.
  • Handling Spikes (Prime Day):
    • The Cart Service is stateless, so we use auto-scaling groups (Kubernetes HPA) to spin up more API servers based on CPU load.
    • We pre-warm the cache and increase database throughput limits before the event.

12. Reliability, failure handling and backpressure

  • Inventory Failure: If the Inventory Service is down, we do not block the user. We allow the "Add to Cart" and show a warning: "Inventory status pending." We resolve the stock check later at checkout.
  • Database Failure: Ideally rare with DynamoDB, but if writes fail, we can temporarily queue requests in a Kafka topic and retry, or degrade to a client-side only cart (Local Storage) and sync when the system recovers.
  • Circuit Breakers: Implemented on calls to the Product Service. If getting price/image fails, we return the cart with "Loading details..." placeholders rather than an error page.

13. Security, privacy and abuse

  • Authentication: Validate JWT tokens at the API Gateway. Ensure request.user_id matches token.user_id.
  • Encryption: All data encrypted in transit (TLS) and at rest (AWS KMS).
  • Abuse Prevention:
    • Max Items: Limit carts to 50 items. This prevents "Inventory Hoarding" attacks where bots add thousands of items to lock up stock.
    • Rate Limiting: Limit "Add to Cart" calls to 60 per minute per user to stop spam bots.

14. Bottlenecks and next steps

  • Bottleneck: Price Syncing. Fetching live prices for 50 items every time a user views the cart is heavy on the Product Service.
    • Next Step: Cache price/metadata objects with a short TTL (e.g., 5 mins) so we don't hit the Product Service on every page refresh.
  • Bottleneck: Abandoned Carts. The DB fills up with millions of old guest carts.
    • Next Step: Aggressively tune the TTL settings to auto-expire anonymous carts after 7 days, keeping only logged-in user carts for longer.

Summary

  1. Architecture: Load Balancer Stateless Cart Service Redis + DynamoDB.

  2. Data: NoSQL key-value model partitioned by UserID for infinite horizontal scale.

  3. Availability: Prioritized over strong consistency to ensure users can always add items.

  4. Key Logic: "Write-Through" caching for speed, and "Merge" logic to unify guest and user sessions.

Design Google Ads
Design Stripe Payment Gateway
Mark as Completed

On this page

1. Problem Definition and Scope

2. Clarify functional requirements

3. Clarify non-functional requirements

4. Back of the envelope estimates

5. API design

6. High level architecture

7. Data model

8. Core flows end-to-end

Flow 1: Add Item to Cart (The Write Path)

Flow 2: View Cart (The Read Path)

Flow 3: The "Merge" (Guest to User)

9. Caching and read performance

10. Storage, indexing and media

11. Scaling strategies

12. Reliability, failure handling and backpressure

13. Security, privacy and abuse

14. Bottlenecks and next steps

Summary